<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Log;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\HttpException;

class EntranceController extends Controller
{
    private $weChat;

    public function __construct()
    {
        $weChat = new WeChatController();
        $this->weChat = $weChat;
    }
    //获取浏览器类型，暂无使用
    function getBrowserType()
    {
        define("BROWSER_TYPE_WX", "WX");
        define("BROWSER_TYPE_AP", "AP");
        $userAgent = $_SERVER['HTTP_USER_AGENT'];
        //Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Mobile/14E304 Nebula PSDType(1) AlipayDefined(nt:WIFI,ws:375|647|3.0) AliApp(AP/10.0.8.032322) AlipayClient/10.0.8.032322 Language/zh-Hans
        //Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Mobile/14E304 MicroMessenger/6.5.7 NetType/WIFI Language/zh_CN
        if (stripos($userAgent, "alipay") !== false || stripos($userAgent, "aliapp") !== false) {
            return BROWSER_TYPE_AP;
        } else if (stripos($userAgent, "messenger") !== false) {
            return BROWSER_TYPE_WX;
        } else {
            return BROWSER_TYPE_PC;
        }
    }

    //服务入口地址
    public function index()
    {
        if (isset($_GET['echostr'])) {
            $this->weChat->valid();
        } else {
            echo $this->weChat->responseMsg();
        }
    }

    //充值中心、查卡详情
    public function recharge()
    {
        $action = isset($_GET['action']) ? $_GET['action'] : '';
        if (($action == 'query_account' || $action == 'detail') && isset($_GET['keyword'])) {
            $account = new AccountController();
            //获取查卡详情
            $info = $account->getAccountDetail();
            return $info;
        }

        if ($action == 'query_product') {
            $productController = new ProductController();
            //获取产品信息
            if (isset($_GET['provider']) && $_GET['provider'] != 'all') {
                $products = $productController->getList($_GET['provider'], [], 0);
            } else if (isset($_GET['esim']) && $_GET['esim'] == 1) {
                $products = $productController->getList('all', [], 1);
            } else {
                $products = $productController->getList('all', [], 0);
            }
            return $products;
        }
        //获取session数据
        $openid = session()->get('openid');
        //获取签名数据
        $configData = $this->weChat->getSignPackage();
        if (!$openid) {
            //没有重新认证授权
            $res = $this->weChat->getOpenid();
            if ($res && isset($_GET['code'])) {
                $configData['openid'] = $res['openid'];
                session()->put('openid', $res['openid']);
            } else {
                $configData['openid'] = '';
            }
        } else {
            //追加openid信息
            $configData['openid'] = $openid;
        }
	$configData['rank'] = '';
        if ($action == 'detail') {
            if ($configData && $configData['openid']) {
                $rank = DB::table('wx_users')->where('openid', $configData['openid'])->value('rank');
                $configData['rank'] = intval($rank);
            }
	    
            return view('detail')->with('configData', $configData);

        } else {
            return view('recharge')->with('configData', $configData);
        }
    }

    //购买中心
    public function buyProduct()
    {
        //获取session数据
        $openid = session()->get('openid');
        //获取签名数据
        $configData = $this->weChat->getSignPackage();
        if (!$openid) {
            //没有重新认证授权
            $res = $this->weChat->getOpenid();
            if ($res && isset($_GET['code'])) {
                $configData['openid'] = $res['openid'];
                session()->put('openid', $res['openid']);
            } else {
                $configData['openid'] = '';
            }
        } else {
            //追加openid信息
            $configData['openid'] = $openid;
        }
        $configData['path_url'] = config('app.url');
        return view('productList')->with('configData', $configData);

    }

    //邮寄
    public function addressProcess()
    {
        $this->weChat->addressProcess();
    }

    //绑定中心
    public function bindInfo()
    {
        $openid = session()->get('openid');
        //获取签名数据
        $configData = $this->weChat->getSignPackage();
        if (!$openid) {
            //没有重新认证授权
            $res = $this->weChat->getOpenid();
            if ($res && isset($_GET['code'])) {
                $configData['openid'] = $res['openid'];
                session()->put('openid', $res['openid']);
            } else {
                $configData['openid'] = '';
            }
        } else {
            $configData['openid'] = $openid;
        }
        if (isset($_GET['action']) && $_GET['action'] == 'list') {
            $bindAccount = new BindAccountController();
            //获取绑定数据
            $data = $bindAccount->getWeChatList($configData['openid']);
            return $data;
        }
        return view('bindAccount')->with('configData', $configData);
    }


    //充值记录
    public function record()
    {
        if (isset($_GET['yearMonth']) || isset($_GET['openid'])) {
            $yearMonth = $_GET['yearMonth'];
            $openid = $_GET['openid'];
            $log = new RechargeLogController();
            $res = $log->list($yearMonth, $openid);
            return $res;
        }

        $openid = session()->get('openid');
        //获取签名数据
        $configData = $this->weChat->getSignPackage();
        if (!$openid) {
            //没有重新认证授权
            $res = $this->weChat->getOpenid();
            if ($res && isset($_GET['code'])) {
                $configData['openid'] = $res['openid'];
                session()->put('openid', $res['openid']);
            } else {
                $configData['openid'] = '';
            }
        } else {
            $configData['openid'] = $openid;
        }
        return view('rechargeLog')->with('configData', $configData);
    }

    //账单详情
    public function rechargeDetail()
    {
        $id = $_GET['id'];
        $log = new RechargeLogController();
        $data = $this->object_to_array($log->detail($id));
        $openid = session()->get('openid');
        if (!$openid) {
            //没有重新认证授权
            $res = $this->weChat->getOpenid();
            if ($res && isset($_GET['code'])) {
                $openid = $res['openid'];
                session()->put('openid', $openid);
            }
        }
        $data['admin_openid'] = false;
        if($openid){
            if($data['openid']===$openid || in_array($openid,['odpqKt4kbTuAk_7pFXuk69Y1BFqs','odpqKt2HuJ9zwz0clCKIA4XkllKw'])){
                if(in_array($openid,['odpqKt4kbTuAk_7pFXuk69Y1BFqs','odpqKt2HuJ9zwz0clCKIA4XkllKw'])){
                    $data['admin_openid'] = true;
                }
                return view('rechargeDetail')->with('data', $data);
            }else{
                throw new HttpException(403,'抱歉，您没有权限查看！');
            }
        }
    }

    //对象转数组
    function object_to_array($obj)
    {
        $obj = (array)$obj;
        foreach ($obj as $k => $v) {
            if (gettype($v) == 'resource') {
                return;
            }
            if (gettype($v) == 'object' || gettype($v) == 'array') {
                $obj[$k] = (array)object_to_array($v);
            }
        }
        return $obj;
    }

    //生成tradeNo
    public function getTradeNo()
    {
        return response([
            'success' => true,
            'out_trade_no' => $this->weChat->makePayOrderId()
        ]);
    }

    //查询订单
    public function payResult()
    {

        $out_trade_no = 0;
        if (isset($_GET['order_id'])) {
            $out_trade_no = $_GET['order_id'];
        }
        $pay = new PayController();
        return $pay->find($out_trade_no);
    }

    //发送消息
    public function sendMsg($openid, $log_id, $msg, $out_trade_no, $vc_product_name, $amount, $remark)
    {
        if(!config('app.wx_send_msg')){
            return true;
        }
        $post_data = array(
            'touser' =>$openid,
            'template_id' =>"5v6r85UauxENyEpGMbRFrxOKHSX5-RBPfz4Zeuxbbo0",
            'url' =>config('app.url')."/api/rechargeDetail?id=".$log_id,
            'data' =>array(
                'first'=>array('value'=>$msg,'color'=> "#173177"),
                'keyword1'=>array('value'=>$out_trade_no,'color'=> "#173177"),
                'keyword2'=>array('value'=>$vc_product_name,'color'=> "#173177"),
                'keyword3'=>array('value'=>$amount,'color'=> "#173177"),
                'remark'=>array('value'=>$remark,'color'=> "#173177")
            )
        );
        return $this->weChat->template_send($post_data);
    }
    //发送消息
//    public function testMsg() {
//        $data = array(
//            'openid'=>'odpqKtxaKoNIs15V3MQWtOAz4dPs',
//            'i_id'=>'1542',
//            'vc_imsi'=>'454006316100298',
//            'out_trade_no'=>'15838193551678926093',
//            'vc_product_name'=>'澳门1天',
//            'amount'=>'11.00'
//        );
//        $nickName = 'Sundy';
//        $this->sendMsg($data['openid'],$data['i_id'],'您好！老板，有新订单了，恭喜'.$nickName.'充值成功！IMSI：'.$data['vc_imsi'].'，Provider：'.'SMT', $data['out_trade_no'], $data['vc_product_name'], $data['amount'],'祝您生活愉快！');
//
//    }

    //支持型号
    public function supportModel()
    {
        return view('supportModel');
    }
}